import { Controller, Get, Post, Body, Param, Delete, Query, HttpStatus } from '@nestjs/common'
import { ConfigService } from '../services/config.service'
import { ConfigEntity } from '../entities/config.entity'
import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiBody, ApiQuery } from '@nestjs/swagger'
import { Response } from 'src/common/interfaces/common'
import { Public } from 'src/common/decorators/public.decorator'
import { DeleteResult } from 'typeorm'

@ApiTags('配置')
@Controller('config')
export class ConfigController {
  constructor(private readonly configService: ConfigService) {}

  /**
   * 获取所有配置（分页）
   * @param page 页码
   * @param limit 每页数量
   */
  @ApiOperation({ summary: '获取所有配置', description: '分页获取系统所有配置项' })
  @ApiQuery({ name: 'page', description: '页码，默认为1', required: false })
  @ApiQuery({ name: 'limit', description: '每页数量，默认为10', required: false })
  @ApiResponse({ status: 200, description: '查询成功' })
  @Public()
  @Get()
  async findAll(
    @Query('page') page: number = 1,
    @Query('limit') limit: number = 10,
  ): Promise<Response<ConfigEntity[]>> {
    const result = await this.configService.findAll(page, limit)
    return {
      statusCode: HttpStatus.OK,
      message: '查询成功',
      data: result.data,
      total: result.total,
    }
  }

  /**
   * 根据键获取配置
   */
  @ApiOperation({ summary: '根据键获取配置', description: '通过配置键获取特定配置项' })
  @ApiParam({ name: 'key', description: '配置键', example: 'site.title' })
  @ApiResponse({ status: 200, type: ConfigEntity, description: '查询成功' })
  @ApiResponse({ status: 404, description: '配置不存在' })
  @Public()
  @Get(':key')
  async findByKey(@Param('key') key: string): Promise<Response<ConfigEntity>> {
    return {
      statusCode: HttpStatus.OK,
      message: '查询成功',
      data: await this.configService.findByKey(key),
    }
  }

  /**
   * 批量获取配置
   */
  @ApiOperation({ summary: '批量获取配置', description: '通过多个配置键批量获取配置项' })
  @ApiQuery({ name: 'keys', description: '配置键列表，用逗号分隔', example: 'site.title,site.logo' })
  @ApiResponse({ status: 200, description: '查询成功' })
  @Public()
  @Get('batch/get')
  async findByKeys(@Query('keys') keys: string): Promise<Response<Record<string, any>>> {
    return {
      statusCode: HttpStatus.OK,
      message: '查询成功',
      data: await this.configService.findByKeys(keys.split(',')),
    }
  }

  /**
   * 删除配置
   */
  @ApiOperation({ summary: '删除配置', description: '删除指定配置项' })
  @ApiParam({ name: 'id', description: '配置ID', example: '1' })
  @ApiResponse({ status: 204, description: '删除成功' })
  @ApiResponse({ status: 404, description: '配置不存在' })
  @Delete(':id')
  async remove(@Param('id') id: string): Promise<Response<DeleteResult>> {
    return {
      statusCode: HttpStatus.NO_CONTENT,
      message: '删除成功',
      data: await this.configService.remove(+id),
    }
  }

  /**
   * 创建配置
   * @throws 409 如果配置键已存在
   */
  @ApiOperation({ summary: '创建配置', description: '创建新的配置项，如果配置键已存在则失败' })
  @ApiBody({
    description: '配置创建参数',
    schema: {
      type: 'object',
      properties: {
        key: { type: 'string', description: '配置键', example: 'site.title' },
        value: { type: 'any', description: '配置值', example: 'VeloAdmin' },
        options: { type: 'object', description: '配置选项', nullable: true },
      },
      required: ['key', 'value'],
    },
  })
  @ApiResponse({ status: 201, type: ConfigEntity, description: '创建成功' })
  @ApiResponse({ status: 409, description: '配置键已存在' })
  @Post('create')
  async createConfig(
    @Body('key') key: string,
    @Body('value') value: any,
    @Body('options') options?: Partial<ConfigEntity>,
  ): Promise<Response<ConfigEntity>> {
    return {
      statusCode: HttpStatus.CREATED,
      message: '创建成功',
      data: await this.configService.create(key, value, options),
    }
  }

  /**
   * 更新配置
   * @throws 404 如果配置不存在
   */
  @ApiOperation({ summary: '更新配置', description: '更新已存在的配置项，如果配置不存在则失败' })
  @ApiBody({
    description: '配置更新参数',
    schema: {
      type: 'object',
      properties: {
        key: { type: 'string', description: '配置键', example: 'site.title' },
        value: { type: 'any', description: '配置值', example: 'VeloAdmin' },
        options: { type: 'object', description: '配置选项', nullable: true },
      },
      required: ['key', 'value'],
    },
  })
  @ApiResponse({ status: 200, type: ConfigEntity, description: '更新成功' })
  @ApiResponse({ status: 400, description: '参数错误' })
  @ApiResponse({ status: 404, description: '配置不存在' })
  @Post('update')
  async updateConfig(
    @Body('key') key: string,
    @Body('value') value: any,
    @Body('options') options?: Partial<ConfigEntity>,
  ): Promise<Response<ConfigEntity>> {
    return {
      statusCode: HttpStatus.OK,
      message: '更新成功',
      data: await this.configService.update(key, value, options),
    }
  }
}
